package cn.sinata.wanglin.village.activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.JsonObject;
import com.hyphenate.easeui.EaseConstant;
import com.xilada.xldutils.activitys.BaseActivity;
import com.xilada.xldutils.activitys.ImagePagerActivity;
import com.xilada.xldutils.adapter.BaseRecyclerAdapter;
import com.xilada.xldutils.adapter.util.SpacesItemDecoration;
import com.xilada.xldutils.adapter.util.ViewHolder;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.DialogUtils;
import com.xilada.xldutils.utils.SharedPreferencesUtils;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sinata.wanglin.R;
import cn.sinata.wanglin.adapter.UserinfoPagerAdapter;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.db.dao.UserDao;
import cn.sinata.wanglin.model.Imageinfo;
import cn.sinata.wanglin.model.Lableinfo;
import cn.sinata.wanglin.model.Userinfo;
import cn.sinata.wanglin.neighbor.activity.ApplyFriendOrGroupActivity;
import cn.sinata.wanglin.neighbor.activity.ChatActivity;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.ResultData;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;
import cn.sinata.wanglin.utils.EMUtils;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

public class AllUserInfoActivity extends BaseActivity implements AppBarLayout.OnOffsetChangedListener{
    @BindView(R.id.ll_loading)
    LinearLayout  ll_loading ;//加载中页面
    @BindView(R.id.ly_show_otheruserinfo)
    RelativeLayout  ly_show_otheruserinfo ;//显示不是好友页面
    @BindView(R.id.ly_show_otheruserinfo_forfriend)
    RelativeLayout ly_show_otheruserinfo_forfriend ;//显示是好友页面
   //不是好友开始
    @BindView(R.id.tv_addfriend)
    TextView tv_addfriend;//好友状态
    //    认证列表 (1:有房认证，2：有车认证，3:学历认证，4:事业认证)
    @BindView(R.id.iv_approve1)
    ImageView iv_approve1;
    @BindView(R.id.iv_approve2)
    ImageView iv_approve2;
    @BindView(R.id.iv_approve3)
    ImageView iv_approve3;
    @BindView(R.id.iv_approve4)
    ImageView iv_approve4;
    @BindView(R.id.tv_mine_wanglinid)
    TextView tv_mine_wanglinid;//开心网邻ID
    @BindView(R.id.tv_mine_username)
    TextView tv_mine_username;//昵称
    @BindView(R.id.headview_mine)
    SimpleDraweeView headview_mine;//头像
    @BindView(R.id.iv_mine_baguatucao)
    TextView iv_mine_baguatucao;//八卦吐槽
    @BindView(R.id.iv_cardetail_servicenum)
    TextView iv_cardetail_servicenum;//邻里好友
    @BindView(R.id.iv_cardetail_goodping)
    TextView iv_cardetail_goodping;//扬言被赞
    @BindView(R.id.tv_birthday)
    TextView tv_birthday;//出身年月日
    @BindView(R.id.tv_industry)
    TextView tv_industry;//行业
    @BindView(R.id.tv_sign)
    TextView tv_sign;//签名
    @BindView(R.id.tv_belonglable)
    TextView tv_belonglable;//归属标签
    @BindView(R.id.rv_alllable)
    RecyclerView rv_alllable;//所有的标签
    @BindView(R.id.rv_allphoto)
    RecyclerView rv_allphoto;//所有的相册
    @BindView(R.id.refreshLayout)
    SwipeRefreshLayout refreshLayout;
    @BindView(R.id.otherAppBar)
    AppBarLayout otherAppBar;
    BaseRecyclerAdapter allphotoAdapter;
    BaseRecyclerAdapter alllableAdapter;
    private ArrayList<Lableinfo> malllabledatas=new ArrayList<Lableinfo>();
    private ArrayList<Imageinfo> mImageinfos=new ArrayList<Imageinfo>();
    @BindView(R.id.toolbar)
    Toolbar toolbar;//
    @BindView(R.id.collapsing_toolbar)
    CollapsingToolbarLayout mCollapsingToolbarLayout;
    //////////////////不是好友结束///////////////
    ////////////////////////////////是好友开始//////////////////////////
    private Userinfo friendUserInfo;
    @BindView(R.id.viewpager)
    ViewPager viewpager;//
    @BindView(R.id.tabs)
    TabLayout tabs;//
    @BindView(R.id.ly_havebeenfriend)
    LinearLayout ly_havebeenfriend;//底部布局
    @BindView(R.id.tv_sendchat_forfriend)
    TextView tv_sendchat_forfriend;//发起对话
    @BindView(R.id.tv_canclefriend_forfriend)
    TextView tv_canclefriend_forfriend;//取消好友
    @BindView(R.id.tv_mine_wanglinid_forfriend)
    TextView tv_mine_wanglinid_forfriend;//开心网邻ID
    @BindView(R.id.tv_mine_username_forfriend)
    TextView tv_mine_username_forfriend;//昵称
    @BindView(R.id.headview_mine_forfriend)
    SimpleDraweeView headview_mine_forfriend;//头像
    @BindView(R.id.iv_mine_baguatucao_forfriend)
    TextView iv_mine_baguatucao_forfriend;//八卦吐槽
    @BindView(R.id.iv_cardetail_servicenum_forfriend)
    TextView iv_cardetail_servicenum_forfriend;//邻里好友
    @BindView(R.id.iv_cardetail_goodping_forfriend)
    TextView iv_cardetail_goodping_forfriend;//扬言被赞
    @BindView(R.id.toolbar_forfriend)
    Toolbar toolbar_forfriend;//
    @BindView(R.id.collapsing_toolbar_forfriend)
    CollapsingToolbarLayout collapsing_toolbar_forfriend;
    @BindView(R.id.appbar)
    AppBarLayout friendAppBar;
   //////////////////是好友结束///////////////
    private String friendID;
    private String friendAccount;
    private String userid;
    private int type = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_user_info);
        ButterKnife.bind(this);
        friendID = getIntent().getExtras().getString("friendID");
        userid = SharedPreferencesUtils.getString(Constant.SP_USERID);
        //type == 1.是聊天页面跳转，没有用户的id。只有im账户。
        type = getIntent().getIntExtra("type",0);
        if (type >= 1) {
            friendAccount = getIntent().getExtras().getString("friendID");
        }
        getUserinfo();
    }
    /**
     * 获取个人信息页面
     *
     */
    private void getUserinfo(){
        ll_loading.setVisibility(View.VISIBLE);
        String friend = friendID;
        if (type >= 1) {
            friend = friendAccount;
        }
        Observable<ResultData<Userinfo>> observable = HttpManager.getUserinfo(userid,friend,type);
        observable.subscribeOn(Schedulers.io())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultDataSubscriber<Userinfo>(this) {
                    @Override
                    public void onSuccess(String msg, Userinfo userinfo) {

                        if (type >= 1) {
                            friendID = userinfo.getId();
                        }
                        ll_loading.setVisibility(View.GONE);
                        //判断是否好友。不是则显示不是好友布局，是的话就显示是好友界面；
                        if("1".equals(userinfo.getIsFriend())||userid.equals(friendID)){
                            //已经是好友，或者是自己
                            ly_show_otheruserinfo_forfriend.setVisibility(View.VISIBLE);
                            ly_show_otheruserinfo.setVisibility(View.GONE);
                            initHaveBeenFriendUserInfo(userinfo);
                        }else{
                            refreshLayout.setRefreshing(false);
                            //不是好友
                            ly_show_otheruserinfo_forfriend.setVisibility(View.GONE);
                            ly_show_otheruserinfo.setVisibility(View.VISIBLE);
                            initOtherUserInfo(userinfo);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        refreshLayout.setRefreshing(false);
                    }
                });
    }

    /**
     * 初始化好友界面
     * @param userinfo
     */
    private void initHaveBeenFriendUserInfo(Userinfo userinfo) {
        friendUserInfo=userinfo;
        setSupportActionBar(toolbar_forfriend);
        toolbar_forfriend.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        friendAppBar.addOnOffsetChangedListener(this);

        collapsing_toolbar_forfriend.setTitle(" ");
        if(userid.equals(friendID)){
            ly_havebeenfriend.setVisibility(View.GONE);
        }

        setupViewPager(userinfo);
    }
    /**
     * 设置用户信息
     * @param userinfo
     */

    private void setFriendData(Userinfo userinfo) {
        if(!TextUtils.isEmpty(userinfo.getCounts())){
            iv_mine_baguatucao_forfriend.setText("八卦吐槽\n"+userinfo.getCounts());
        }else{
            iv_mine_baguatucao_forfriend.setText("八卦吐槽\n0");
        }
        if(!TextUtils.isEmpty(userinfo.getFriends())){
            iv_cardetail_servicenum_forfriend.setText("邻里好友\n"+userinfo.getFriends());
        }else{
            iv_cardetail_servicenum_forfriend.setText("邻里好友\n0");
        }
        if(!TextUtils.isEmpty(userinfo.getLikes())){
            iv_cardetail_goodping_forfriend.setText("扬言被赞\n"+userinfo.getLikes());
        }else{
            iv_cardetail_goodping_forfriend.setText("扬言被赞\n0");
        }
        if(!TextUtils.isEmpty(userinfo.getHeadUrl())){
            headview_mine_forfriend.setImageURI(userinfo.getHeadUrl());
        }
        if(!TextUtils.isEmpty(userinfo.getId())){
            tv_mine_wanglinid_forfriend.setText("ID:"+userinfo.getAccount());
        }
        if(!TextUtils.isEmpty(userinfo.getNickName())){
            tv_mine_username_forfriend.setText(userinfo.getNickName());
        }
        if(TextUtils.isEmpty(userinfo.getSex())||"1".equals(userinfo.getSex())){
            Resources res = getResources();
            Drawable img_off = res.getDrawable(R.mipmap.gril);
            // 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
            img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
            tv_mine_username_forfriend.setCompoundDrawables(null, null, img_off, null); //设置右图标
        }else{
            Resources res = getResources();
            Drawable img_off = res.getDrawable(R.mipmap.boy);
            // 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
            img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
            tv_mine_username_forfriend.setCompoundDrawables(null, null, img_off, null); //设置右图标
        }

    }

    private void setupViewPager(Userinfo userinfo) {
        ArrayList<String> titles = new ArrayList<String>();
        titles.add("个人信息");
        titles.add("圈子八卦");
        titles.add("小区活动");
        UserinfoPagerAdapter adapter = new UserinfoPagerAdapter(getSupportFragmentManager(),titles,friendID);
        viewpager.setOffscreenPageLimit(3);
        viewpager.setAdapter(adapter);
        tabs.setupWithViewPager(viewpager);
        setFriendData(userinfo);
    }

    /**
     * 初始化
     * @param userinfo
     */
    private void initOtherUserInfo(Userinfo userinfo) {
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getUserinfo();
            }
        });
        mCollapsingToolbarLayout.setTitle(" ");
        if(alllableAdapter==null) {
            GridLayoutManager mgr = new GridLayoutManager(AllUserInfoActivity.this, 3);
            rv_alllable.setLayoutManager(mgr);
            alllableAdapter = new BaseRecyclerAdapter<Lableinfo>(malllabledatas, R.layout.item_personalllable) {
                @Override
                public void onBind(final int position, final Lableinfo data, ViewHolder holder) {
                    holder.setText(R.id.tv_mylable, data.getName());
                }
            };
            rv_alllable.setAdapter(alllableAdapter);
        }
        if(allphotoAdapter==null){
            rv_allphoto.setLayoutManager(new LinearLayoutManager(AllUserInfoActivity.this, LinearLayoutManager.HORIZONTAL, false));
            rv_allphoto.addItemDecoration(new SpacesItemDecoration(3));
            allphotoAdapter= new BaseRecyclerAdapter<Imageinfo>(mImageinfos, R.layout.item_myimage_grid_nodelete) {
                @Override
                public void onBind(final int position, final Imageinfo data, ViewHolder holder) {
                    ((SimpleDraweeView) holder.bind(R.id.image)).setImageURI(data.getImgUrl());
                }
            };
            allphotoAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    ArrayList<String> showPhoto=new ArrayList<String>();
                    for(int i=0;i<mImageinfos.size();i++){
                        showPhoto.add(mImageinfos.get(i).getImgUrl());

                    }
                    ActivityUtil.create(AllUserInfoActivity.this).go(ImagePagerActivity.class)
                            .put(ImagePagerActivity.URLS,showPhoto)
                            .put(ImagePagerActivity.CURRENT_POSITION,position)
                            .start();
                }
            });
            rv_allphoto.setAdapter(allphotoAdapter);
        }

        otherAppBar.addOnOffsetChangedListener(this);

        setUserData(userinfo);
    }
    /**
     * 设置用户信息
     * @param userinfo
     */

    private void setUserData(Userinfo userinfo) {
        if(!TextUtils.isEmpty(userinfo.getCounts())){
            iv_mine_baguatucao.setText("八卦吐槽\n"+userinfo.getCounts());
        }else{
            iv_mine_baguatucao.setText("八卦吐槽\n0");
        }
        if(!TextUtils.isEmpty(userinfo.getFriends())){
            iv_cardetail_servicenum.setText("邻里好友\n"+userinfo.getFriends());
        }else{
            iv_cardetail_servicenum.setText("邻里好友\n0");
        }
        if(!TextUtils.isEmpty(userinfo.getLikes())){
            iv_cardetail_goodping.setText("扬言被赞\n"+userinfo.getLikes());
        }else{
            iv_cardetail_goodping.setText("扬言被赞\n0");
        }
        if(!TextUtils.isEmpty(userinfo.getHeadUrl())){
            headview_mine.setImageURI(userinfo.getHeadUrl());
        }
        if(!TextUtils.isEmpty(userinfo.getId())){
            tv_mine_wanglinid.setText("ID:"+userinfo.getAccount());
        }
        if(!TextUtils.isEmpty(userinfo.getNickName())){
            tv_mine_username.setText(userinfo.getNickName());
        }
        if(TextUtils.isEmpty(userinfo.getSex())||"1".equals(userinfo.getSex())){
            Resources res = getResources();
            Drawable img_off = res.getDrawable(R.mipmap.gril);
            // 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
            img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
            tv_mine_username.setCompoundDrawables(null, null, img_off, null); //设置右图标
        }else{
            Resources res = getResources();
            Drawable img_off = res.getDrawable(R.mipmap.boy);
            // 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
            img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
            tv_mine_username.setCompoundDrawables(null, null, img_off, null); //设置右图标
        }
        if(!TextUtils.isEmpty(userinfo.getBirthday())){
            tv_birthday.setText(userinfo.getBirthday());
        }
        if(!TextUtils.isEmpty(userinfo.getIndustry())){
            tv_industry.setText(userinfo.getIndustry());
        }
        if(!TextUtils.isEmpty(userinfo.getCharacter())){
            tv_sign.setText(userinfo.getCharacter());
        }

        if(!TextUtils.isEmpty(userinfo.getBelongLabel())){
            tv_belonglable.setText(userinfo.getBelongLabel());
            tv_belonglable.setVisibility(View.VISIBLE);
        }else{
            tv_belonglable.setVisibility(View.GONE);
        }
        malllabledatas.clear();
        if(!TextUtils.isEmpty(userinfo.getOtherLabel())){
            String[] sourceStrArray =userinfo.getOtherLabel().split(",");
            for(int i=0;i<sourceStrArray.length;i++){
                malllabledatas.add(new Lableinfo(sourceStrArray[i],false));
            }

        }
        alllableAdapter.notifyDataSetChanged();
        mImageinfos.clear();
        if(userinfo.getImgList()!=null&&userinfo.getImgList().size()!=0){
            mImageinfos.addAll(userinfo.getImgList());
        }
        allphotoAdapter.notifyDataSetChanged();
        if(userinfo.getApproveList()!=null&&userinfo.getApproveList().size()!=0){
            for(int i=0;i<userinfo.getApproveList().size();i++){
                if("A".equals(userinfo.getApproveList().get(i))){
                    iv_approve1.setVisibility(View.VISIBLE);
                    if("1".equals(userinfo.getOwnerAuthType())){
                        iv_approve1.setImageResource(R.mipmap.ic_havehouse1);
                    }else if ("2".equals(userinfo.getOwnerAuthType())){
                        iv_approve1.setImageResource(R.mipmap.ic_havehouse2);
                    }else{
                        iv_approve1.setImageResource(R.mipmap.ic_havehouse0);
                    }
                }else if("B".equals(userinfo.getApproveList().get(i))){
                    iv_approve2.setVisibility(View.VISIBLE);
                }else if("C".equals(userinfo.getApproveList().get(i))){
                    iv_approve3.setVisibility(View.VISIBLE);
                }else if("D".equals(userinfo.getApproveList().get(i))){
                    iv_approve4.setVisibility(View.VISIBLE);
                }
            }
        }else{
            iv_approve1.setVisibility(View.GONE);
            iv_approve2.setVisibility(View.GONE);
            iv_approve3.setVisibility(View.GONE);
            iv_approve4.setVisibility(View.GONE);
        }
        String userid= SharedPreferencesUtils.getString(Constant.SP_USERID);
        if(userid.equals(friendID)){
            tv_addfriend.setVisibility(View.GONE);
        }
        //与查看好友是否为好友（0：接受 1：验证通过 2：添加 3：等待验证 4：拒绝）
        if(!TextUtils.isEmpty(userinfo.getIsFriend())){
            if("3".equals(userinfo.getIsFriend())){
                tv_addfriend.setText("待通过");
                tv_addfriend.setBackgroundColor(getResources().getColor(R.color.disableColor));
                tv_addfriend.setEnabled(false);
                tv_addfriend.setVisibility(View.VISIBLE);
            } else if("2".equals(userinfo.getIsFriend())){
                tv_addfriend.setText("添加好友");
                tv_addfriend.setBackgroundColor(getResources().getColor(R.color.app_theme_color));
                tv_addfriend.setVisibility(View.VISIBLE);
            }else{
                tv_addfriend.setVisibility(View.GONE);
            }
        }else{
            tv_addfriend.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.moremenu, menu);

        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_more:
                if(!userid.equals(friendID)){
                    ActivityUtil.create(mContext).go(UserDetailMoreActivity.class).put("friendId",friendID)
                            .startForResult(2);
                }else{
                    showToast("亲!自己不能举报自己哦！");
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (resultCode){
            case 1:
                //屏蔽
                DialogUtils.createNoticeDialog(mContext, "提示", "你将不会看到Ta发布的所有的信息,\n可在\"设置-隐私-已屏蔽的人\"中解除", false, "确定", "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        showDialog("屏蔽中...");
                        shieldOrBlack("0");
                    }
                }, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
                break;
            case 2:
                //拉黑
                DialogUtils.createNoticeDialog(mContext, "提示", "拉入黑名单以后:\n你将看不到Ta发的任何信息\nTa也将无法与你发起聊天。可以在\n\"设置-隐私-黑名单管理\"中解除", false, "确定", "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        showDialog("拉黑中...");
                        shieldOrBlack("1");
                    }
                }, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
                break;
            case RESULT_OK:
                if (requestCode == 21) {
                     finish();
                }
                break;
        }


    }

    /**
     * 类型 0：屏蔽；1:黑名单
     * @param blackType
     */
    public void shieldOrBlack(String blackType){
        HttpManager.shieldOrBlack(userid,friendID,blackType).subscribe(new ResultDataSubscriber<JsonObject>(this) {
            @Override
            public void onSuccess(String msg, JsonObject jsonObject) {
                showToast(msg);
            }
        });

    }

    @OnClick({R.id.tv_addfriend,R.id.tv_sendchat_forfriend,R.id.tv_canclefriend_forfriend})
    void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.tv_addfriend:
                ActivityUtil.create(this)
                        .go(ApplyFriendOrGroupActivity.class)
                        .put("id",friendID)
                        .startForResult(21);
                break;
            case R.id.tv_sendchat_forfriend:

                if (type == 1) {
                    finish();
                } else {
                    UserDao.getInstance(mContext).saveUser(friendUserInfo.getAccount(),friendUserInfo.getNickName(),friendUserInfo.getHeadUrl());
                    ActivityUtil.create(mContext)
                            .go(ChatActivity.class)
                            .put(EaseConstant.EXTRA_CHAT_TYPE,EaseConstant.CHATTYPE_SINGLE)
                            .put(EaseConstant.EXTRA_USER_ID,friendUserInfo.getAccount())
                            .start();
                }
                break;
            case R.id.tv_canclefriend_forfriend:
//                //描述:
//                finish();
                cancelFriend();
                break;
        }
    }

    void cancelFriend(){

        showDialog();
        HttpManager.cancelFriend(userid,friendID)
                .subscribe(new ResultDataSubscriber<JsonObject>(this) {
                    @Override
                    public void onSuccess(String msg, JsonObject jsonObject) {
                        EMUtils.deleteConversation(friendUserInfo.getAccount());
                        showToast(msg);
                        setResult(Constant.ResultCode_CANCEL_FRIEND);
                        finish();
                    }
                });
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        if (verticalOffset >= 0) {
            refreshLayout.setEnabled(true);
        } else {
            refreshLayout.setEnabled(false);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            friendAppBar.removeOnOffsetChangedListener(this);
            otherAppBar.removeOnOffsetChangedListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener listener){
        if (friendAppBar != null) {
            friendAppBar.addOnOffsetChangedListener(listener);
        }
    }

    public void removeOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener listener){
        if (friendAppBar != null) {
            friendAppBar.removeOnOffsetChangedListener(listener);
        }
    }
}
